<script setup>
import { ref, computed } from 'vue'
import { showSuccessToast, showFailToast } from 'vant'
import axios from '@/utils/axios.js'
import {useRoute} from "vue-router";
import {useUserStore} from "@/stores/user.js";

const users = useUserStore().user
const route = useRoute()

const email = ref('')
const verificationCode = ref('')
const isCountdown = ref(false)
const countdown = ref(60)

// 计算属性：验证表单是否有效
const isFormValid = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  const codeRegex = /^\d{6}$/
  return emailRegex.test(email.value) && codeRegex.test(verificationCode.value)
})

// 发送验证码
const sendVerificationCode = () => {
    axios.get(`api/sendCode/${email.value}`)
        .then((res) => {
          ElMessage({
            message:res.msg,
            duration: 2000,
            type: 'success',
          })
        })

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email.value)) {
    ElMessage.error('请输入有效的邮箱地址')
    return
  }

  // 启动倒计时
  isCountdown.value = true
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value === 0) {
      clearInterval(timer)
      isCountdown.value = false
      countdown.value = 60
    }
  }, 1000)
}

const add =()=>{
  axios.get(`/api/users/updateEmail/${users.userId}/${email.value}`)
}

// 绑定邮箱事件
const bindEmail = () => {
  axios.get(`api/verify/${email.value}/${verificationCode.value}`)
      .then((res) => {
        if (res.code === 200) {
          ElMessage({
            message:res.msg,
            duration: 1500,
            type: 'success',
            onClose:()=>{
              add()
            }
          })
        }else{
          ElMessage({
            message:res.msg,
            duration: 1500,
            type: 'error',
            onClose:()=>{
              add()
            }
          })
        }

      })
}
</script>

<template>
  <div class="email-bind-page">
    <van-nav-bar title="邮箱绑定" left-arrow @click-left="$router.back()" />

    <div class="bind-content">
      <div class="bind-status">
        <van-icon name="envelope" color="#ff976a" size="24px" />
        <h2>邮箱未绑定</h2>
        <p>绑定邮箱后，您可以：</p>
        <ul class="benefits-list">
          <li><span class="number-circle">①</span>接收账户安全通知</li>
          <li><span class="number-circle">②</span>找回忘记的密码</li>
          <li><span class="number-circle">③</span>接收小鸡词典的最新动态</li>
        </ul>
      </div>

      <div class="bind-form">
        <h3>绑定新邮箱</h3>

        <van-field
            v-model="email"
            label="邮箱地址"
            type="email"
            placeholder="请输入您的邮箱"
            clearable
        />

        <van-field
            v-model="verificationCode"
            label="验证码"
            placeholder="请输入6位验证码"
            clearable
            :formatter="(value) => value.replace(/\D/g, '').slice(0, 6)"
        >
          <template #button>
            <van-button
                size="small"
                :disabled="isCountdown"
                @click="sendVerificationCode"
                color="linear-gradient(to right, #ff6034, #ff976a)"
            >
              {{ isCountdown ? `${countdown}秒后重新发送` : '发送验证码' }}
            </van-button>
          </template>
        </van-field>

        <div class="bind-btn-container">
          <van-button
              round
              block
              type="primary"
              :color="isFormValid ? 'linear-gradient(to right, #ff6034, #ff976a)' : 'linear-gradient(to right, #969799, #7d7e80)'"
              @click="bindEmail"
              :disabled="!isFormValid"
          >
            绑定邮箱
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.email-bind-page {
  height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.bind-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.bind-status {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.bind-status h2 {
  margin: 12px 0 16px;
  font-size: 18px;
  font-weight: 600;
  color: #323233;
}

.bind-status p {
  margin-bottom: 16px;
  color: #646566;
  font-size: 14px;
}

.benefits-list {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: left;
}

.benefits-list li {
  margin-bottom: 12px;
  color: #323233;
  display: flex;
  align-items: center;
}

.number-circle {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  background-color: #ff976a;
  color: white;
  border-radius: 50%;
  margin-right: 8px;
  font-size: 12px;
}

.bind-form {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.bind-form h3 {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.bind-btn-container {
  margin-top: 24px;
}

:deep(.van-field) {
  padding-left: 0;
  padding-right: 0;
}

:deep(.van-field__label) {
  width: 60px;
  color: #323233;
}

:deep(.van-cell::after) {
  border-bottom: 1px solid #ebedf0;
}
</style>